package com.et114.components.ehcache;

import java.io.Serializable;
import java.util.List;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.springframework.util.Assert;

import com.et114.core.exception.CheckException;

/*
 * @author guanhw
 */
public class EhCacheUtils {
	
	/**
	 * 
	 * @param cache
	 * @param key
	 * @param value
	 * @throws CheckException
	 */
	public static void put( Ehcache cache , Object key , Object value  ) throws CheckException {
		Assert.notNull ( cache , "cache is null !" )  ;
		Assert.notNull ( key , "key is null !" )  ;
		Assert.notNull ( value , "value is null !" )  ;
		Element element = new Element ( key , value )  ;
		cache.remove ( key ) ; 
		cache.put ( element );
	}
	
	/**
	 * 
	 * @param cache
	 * @param ec
	 * @throws CheckException
	 */
	public static void put( Ehcache cache , ICache ec ) throws CheckException {
		Assert.notNull ( cache , "cache is null !" )  ;
		Assert.notNull ( ec , "ec is null !" )  ;
		Element element = new Element ( ec.getKey () , ec )  ;
		cache.remove ( ec.getKey ( ) ) ; 
		cache.put ( element );
	}
	
	/**
	 * 
	 * @param cache
	 * @param key
	 * @return
	 * @throws CheckException
	 */
	public static boolean remove( Ehcache cache , Serializable key )  throws CheckException {
		Assert.notNull ( cache , "cache is null !" )  ;
		Assert.notNull ( key , "key is null !" )  ;
		boolean st = cache.remove ( key ) ;
		return  st;
	}
	
	/**
	 * 
	 * @param cache
	 * @param key
	 * @return
	 * @throws CheckException
	 */
	public static ICache get( Ehcache cache , Serializable key ) throws CheckException {
		Assert.notNull ( cache , "cache is null !" )  ;
		Assert.notNull ( key , "key is null !" )  ;
		Element e = cache.get ( key ) ;
		return ( ICache )e.getValue ( );
	}
	
	
	/**
	 * 
	 * @param cache
	 * @param key
	 * @return
	 * @throws CheckException
	 */
	public static Object getValue( Ehcache cache , Object key ) throws CheckException {
		Assert.notNull ( cache , "cache is null !" )  ;
		Assert.notNull ( key , "key is null !" )  ;
		Element e = cache.get ( key ) ;
		return e.getValue ( );
	}
	/**
	 * 
	 * @param cache
	 * @return
	 * @throws CheckException
	 */
	public static List listKeys( Ehcache cache ) throws CheckException  {
		Assert.notNull ( cache , "cache is null !" )  ;
		/*
		List keys = cache.getKeys ( ) ; 
		return keys.toArray ( new Serializable[ keys.size ( ) ] );
		*/
		return cache.getKeys ( );
	}
	
}
